import BaseEvent from '@/components/events/BaseEvent'
import { EventBus } from '@/store/index'
import { getCompIdByParam } from '@/plugins/utils'

export default class ShakeEvent extends BaseEvent{
  constructor() {
    super();
  }


  static instance_;
	static get shakeEvent() {
		if (!ShakeEvent.instance_) {
			ShakeEvent.instance_ = new ShakeEvent()
		}
		return ShakeEvent.instance_
  }
  
  initShakeData({item, event, isPostWbEventOrCommonEvents}){
    this.item = item;
    this.event = event;
    this.isPostWbEventOrCommonEvents = isPostWbEventOrCommonEvents;
  }
  
  excute({item, event}){
    this.item = item;
    this.event = event;

    this.onShakeEvent();
  }

  initShake(){
    this.shakeCb = window.setInterval(() => {
      if(window.Shake){
        window.clearInterval(this.shakeCb);
        if(!window.shakeEvent){
          window.shakeEvent = new window.Shake({
              threshold: 8, // 摇动阈值
              timeout: 500 // 事件发生频率，是可选值
          });
        }
        this.permissionShake();
        window.shakeEvent.start();
      }
    }, this.siteInfo.reloadTime)
  }

  permissionShake() {
    window.removeEventListener('shake', this.onShakeEvent);
    if (typeof(window.DeviceMotionEvent) !== "undefined" && typeof window.DeviceMotionEvent.requestPermission === 'function') {
      window.DeviceMotionEvent.requestPermission()
        .then(permissionState => {
          if (permissionState === 'granted') {
            // window.addEventListener('devicemotion', () => {});
            window.addEventListener('shake', this.onShakeEvent, false);
          }
        })
        .catch(console.error);
    } else {
      window.addEventListener('shake', this.onShakeEvent, false);
      // handle regular non iOS 13+ devices
    }
  }

  onShakeEvent(){
    window.removeEventListener('shake', this.onShakeEvent);
    if(window.shakeEvent) {
      window.shakeEvent.reset();
      window.shakeEvent.stop();
    }
    let event = this.event;
    this.onShake(event);
    this.onVibrate();

    // 判断是否有关联id
    const relateId = getCompIdByParam(event.comps[0].attrs.value)
    // 有关联id，则执行关联id组件的事件
    if(relateId) {
      EventBus.$emit("itemClick", {id: relateId, index: 0, e: null});
      // 执行本身组件 除“摇一摇”以外 其他所有事件
      this.isPostWbEventOrCommonEvents({ loadEvent: null, e: null });
    }else{
      const popId = getCompIdByParam(event.comps[1].attrs.value);
      if(popId > 0){
        this.showPop(popId);
      }
      const pageId = getCompIdByParam(event.comps[2].attrs.value);
      if(pageId > 0){
        this.showPage(pageId);
      }
      const link = getCompIdByParam(event.comps[3].attrs.value);
      if(link && link.length > 0){
        this.openLinkBySelfUrl(link);
      }
    }
  }

  onShake(event){
    let rotateUrl
    if (this.item.lists && this.item.lists.length > 0) {
      let randomIndex = _.random(0, this.item.lists.length - 1)
      rotateUrl = this.item.lists[randomIndex].url
    }
    if (rotateUrl) {
      let shareData = { url: rotateUrl }
      this.store.commit('updateShareData', shareData)
    }

    let popId = parseInt(event.comps[1].attrs.value)
    let pageId = parseInt(event.comps[2].attrs.value)
    if (popId && popId > 0) {
      this.showPop(popId)
    } else if (pageId && pageId > 0) {
      this.showPage(pageId)
    } else {
      let url = event.comps[3].attrs.value
      if (url.length > 0) {
        this.openLinkBySelfUrl(url);
      }
    }
  }

  onVibrate() {
    if("vibrate" in window.navigator) {
      window.navigator.vibrate([200, 100, 200]);
    }
  }

  destroy(){
    super.destroy();
  }
}